// 自定义 右击 hook

import { useRef, useEffect } from 'react';

const remote = window.require('@electron/remote');
const { Menu } = remote;

const useContextMenu = (contextMenuTmp, areaClass) => {
  const currentEle = useRef(null);

  useEffect(() => {
    // 获取需要触发右键菜单区域的元素
    const areaEle = document.querySelector(areaClass);

    // 创建 menu
    const menu = Menu.buildFromTemplate(contextMenuTmp);
    // 自定义右键操作事件监听
    const contextMenuHandle = ev => {
      if (areaEle.contains(ev.target)) {
        currentEle.current = ev.target;
        menu.popup({ window: remote.getCurrentWindow });
      }
    };
    window.addEventListener('contextmenu', contextMenuHandle);
    return () => {
      window.removeEventListener('contextmenu', contextMenuHandle);
    };
  });
  return currentEle;
};

export default useContextMenu;
